from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, HttpResponse
from io import BytesIO
from django.contrib import messages
from django import forms
from app02 import models
from app02.utils.bootrstap import BootrsapForm, BootrsapModelForm
from app02.utils.code import check_code
from app02.utils.encrypt import md5
from django.core.exceptions import ValidationError



# 登录界面
class LoginModelForm(BootrsapForm):
    user = forms.CharField(
        label='用户名',
        required=True,
        min_length=2,
        max_length=10,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        error_messages={
            'required': '用户名不能为空',
            'min_length': '长度不能小于2个字符',
            'max_length': '长度不能大于10个字符'
        }
    )
    pwd = forms.CharField(
        label='密码',
        required=True,
        min_length=3,
        max_length=32,
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        error_messages={
            'required': '密码不能为空',
            'min_length': '长度不能小于3个字符',
            'max_length': '长度不能大于32个字符'
        }
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )
    # # 给密码进行md5加密
    # def clean_password(self):
    #     pwd=self.cleaned_data.get('pwd')
    #     return md5(pwd)


def login_list(request):
    if request.method == 'GET':
        form = LoginModelForm()
        return render(request, 'login.html', {"form": form})
    else:
        form = LoginModelForm(data=request.POST)
        h_type = request.POST.get('h_type')
        if form.is_valid():
            # 验证码的效验
            # 将验证码从数组中删除出来并返回  {'user': 'chen', 'pwd': '11111111111111', 'code': '10858'}
            code_input = form.cleaned_data.pop('code')
            # 获取生成的验证码
            codes = request.session.get('image_code')
            # 当用户输入的验证码不等于生成验证码时返回错误提示
            if code_input != codes:
                form.add_error('code', '验证码错误！')
                return render(request, 'login.html', {"form": form})
            # print(type(h_type)  )
            if h_type == '0':
                pwd = md5(form.cleaned_data.get('pwd'))
                user = form.cleaned_data.get('user')
                # 获去到数据到数据库中校验
                teach_content = models.TeachInfo.objects.filter(user=user, pwd=pwd,h_type=h_type).first()
                # 当获取数据为none时
                print(form.cleaned_data)
                if not teach_content:
                    form.add_error('pwd', '用户名或者密码错误')
                    return render(request, 'login.html', {"form": form})
                # 用户名跟密码正确
                request.session['info'] = {'id': teach_content.id, 'user': teach_content.user,'h_type':teach_content.h_type}
                # session可以保留七天
                request.session.set_expiry(60 * 60 * 24 * 7)
                messages.error(request, '登录成功')
                return redirect('/teacher/list/')
            elif h_type == '1':
                user = form.cleaned_data.get('user')
                pwd = md5(form.cleaned_data.get('pwd'))
                # 获去到数据到数据库中校验
                student_content = models.StudentInfo.objects.filter(user=user, pwd=pwd,h_type=h_type).first()
                # 当获取数据为none时
                if not student_content:
                    form.add_error('pwd', '用户名或者密码错误')
                    return render(request, 'login.html', {"form": form})
                else:
                    # 用户名跟密码正确
                    request.session['info'] = {'id': student_content.id, 'user': student_content.user,
                                               'h_type': student_content.h_type}
                    # session可以保留1天
                    request.session.set_expiry(60 * 60 * 24)
                    messages.error(request, '登录成功')
                    return redirect('/student/list/')
            elif h_type == '2':
                user = form.cleaned_data.get('user')
                pwd = md5(form.cleaned_data.get('pwd'))
                # 获去到数据到数据库中校验
                admin_content = models.AdminInfo.objects.filter(user=user, pwd=pwd,h_type=h_type).first()
                # 当获取数据为none时
                if not admin_content:
                    form.add_error('pwd', '用户名或者密码错误')
                    return render(request, 'login.html', {"form": form})
                # 用户名跟密码正确
                request.session['info'] = {'id': admin_content.id, 'user': admin_content.user,'h_type':admin_content.h_type}
                # session可以保留七天
                request.session.set_expiry(60 * 60 * 24 * 7)
                messages.error(request, '登录成功')
                return redirect('/admins/list/')
            else:
                return render(request, 'login.html', {"form": form})
            # # print( form.cleaned_data )
            # user_s=form.cleaned_data['user']
            # print(user_s)
    return render(request, 'login.html', {"form": form})


# 生成随机验证码
def image_code(request):
    """生成验证码图片"""

    # 调用pillow函数，生成图片
    img, code_string = check_code()
    print(code_string)
    # 写入到session中(以便后面获取验证码进行校验)
    request.session['image_code'] = code_string
    # 给session设置超时60s
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())


#注册界面
class SignForm( BootrsapForm ):
    user = forms.CharField(
        label='用户名',
        required=True,
        min_length=2,
        max_length=10,
        widget=forms.TextInput( attrs={'class': 'form-control'} ),
        error_messages={
            'required': '用户名不能为空',
            'min_length': '长度不能小于2个字符',
            'max_length': '长度不能大于10个字符'
        }
    )
    pwd = forms.CharField(
        label='密码',
        required=True,
        min_length=3,
        max_length=32,
        widget=forms.PasswordInput( attrs={'class': 'form-control'} ),
        error_messages={
            'required': '用户名不能为空',
            'min_length': '长度不能小于3个字符',
            'max_length': '长度不能大于32个字符'
        }
    )
    # 创建一个字段
    com_password = forms.CharField(
        label='确认密码',
        # 保留原密码的值render_value=True
        widget=forms.PasswordInput( render_value=True )
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )

    # # 给密码进行md5加密
    # def clean_password(self):
    #     pwd = self.cleaned_data.get( 'pwd' )
    #     return md5( pwd )

def sign_list(request):
    if request.method == 'GET':
        form = SignForm()
        return render( request, 'sign.html', {'form': form} )
    else:
        form = SignForm( data=request.POST )
        h_type = request.POST.get( 'h_type' )
        # print(h_type)
        if form.is_valid():
            # 验证码的效验
            # 将验证码从数组中删除出来并返回  {'user': 'chen', 'pwd': '11111111111111', 'code': '10858'}
            code_input = form.cleaned_data.pop( 'code' )
            # 获取生成的验证码
            codes = request.session.get( 'image_code' )
            # 当用户输入的验证码不等于生成验证码时返回错误提示
            if code_input != codes:
                form.add_error( 'code', '验证码错误！' )
                return render( request, 'sign.html', {"form": form} )
            if h_type == '0':
                # 获取到验证通过用户输入的确认密码，通过md5给密码加密
                comstf = md5( form.cleaned_data.get( 'com_password' ) )
                # 获取到用户输入的密码
                pwd =md5(form.cleaned_data.get( 'pwd' ))
                if comstf !=pwd:
                    form.add_error( 'com_password', '两次输入密码不一致！' )
                    return render( request,'sign.html', {"form": form})
                user=form.cleaned_data.get('user')
                models.TeachInfo.objects.create(user=user,pwd=pwd,h_type=h_type)
                messages.error(request, '注册成功')
                return redirect( '/account/login/' )
            elif h_type == '1':
                # 获取到验证通过用户输入的确认密码，通过md5给密码加密
                comstf = md5( form.cleaned_data.get( 'com_password' ) )
                # 获取到用户输入的密码
                pwd = md5( form.cleaned_data.get( 'pwd' ) )
                if comstf != pwd:
                    form.add_error( 'com_password', '两次输入密码不一致！' )
                    return render( request, 'sign.html', {"form": form} )
                else:
                    name = form.cleaned_data.get('user')
                    models.StudentInfo.objects.create(user=name, pwd=pwd, h_type=h_type)
                    messages.error(request, '注册成功')
                    return HttpResponseRedirect( '/account/login/' )
            # elif h_type == '2':
            #     # 获取到验证通过用户输入的确认密码，通过md5给密码加密
            #     comstf = md5( form.cleaned_data.get( 'com_password' ) )
            #     # 获取到用户输入的密码
            #     pwd = md5( form.cleaned_data.get( 'pwd' ) )
            #     if comstf != pwd:
            #         form.add_error( 'com_password', '两次输入密码不一致！' )
            #         return render( request, 'sign.html', {"form": form} )
            #     name = form.cleaned_data.get( 'user' )
            #     models.AdminInfo.objects.create( user=name, pwd=pwd,h_type=h_type)
            #     messages.error(request, '注册成功')
            #     return redirect( '/account/login/' )
            else:
                return render( request, 'login.html', {"form": form} )

    return render( request, 'sign.html', {"form": form} )

#注销
def account_logout(request):
    request.session.clear()
    return redirect('/index/list/')